package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbGroupActive;
import com.bwie.service.TbGroupActiveService;
import com.bwie.mapper.TbGroupActiveMapper;
import com.bwie.utils.R;
import com.bwie.vo.ActiveVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;

/**
* @author 31439
* @description 针对表【tb_group_active(拼团活动表)】的数据库操作Service实现
* @createDate 2025-07-28 09:39:57
*/
@Service
public class TbGroupActiveServiceImpl extends ServiceImpl<TbGroupActiveMapper, TbGroupActive>
    implements TbGroupActiveService{

    @Autowired
    TbGroupActiveMapper tbGroupActiveMapper;

    @Override
    public R activeList(ActiveVo activeVo) {
        Page<TbGroupActive> page = new Page<>(activeVo.getPageNum(), activeVo.getPageSize());
        Page<TbGroupActive> groupActivePage = tbGroupActiveMapper.activeList(page,activeVo);
        return R.OK(groupActivePage);
    }

    @Override
    public R addActive(TbGroupActive tbGroupActive) {
        //判断活动是否已经存在
        TbGroupActive selectOne = tbGroupActiveMapper.selectOne(new QueryWrapper<TbGroupActive>().lambda()
                .eq(TbGroupActive::getActiveName, tbGroupActive.getActiveName())
        );
        if(selectOne != null){
            return R.ERROR(500,"该活动已存在");
        }

        //排序
        QueryWrapper<TbGroupActive> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(TbGroupActive::getBeginTime);
        //判断时间是否正确
        long beginTime = tbGroupActive.getBeginTime().getTime();
        long endTime = tbGroupActive.getEndTime().getTime();
        if(beginTime > endTime){
            return R.ERROR(500,"开始时间应该早于结束时间");
        }
        tbGroupActive.setCreatedTime(new Date());
        tbGroupActive.setCreatedBy("张三");
        tbGroupActiveMapper.insert(tbGroupActive);
        return R.OK();
    }

    @Override
    public R updateActive(TbGroupActive tbGroupActive) {
        //判断时间是否正确
        long beginTime = tbGroupActive.getBeginTime().getTime();
        long endTime = tbGroupActive.getEndTime().getTime();
        if(beginTime > endTime){
            return R.ERROR(500,"开始时间应该早于结束时间");
        }
        tbGroupActiveMapper.updateById(tbGroupActive);
        return R.OK();
    }

    @Override
    public R deleteActive(Integer activeId) {
        //先判断活动是否存在
        TbGroupActive tbGroupActive = tbGroupActiveMapper.selectById(activeId);
        if(tbGroupActive == null){
            return R.ERROR(500,"该活动不存在");
        }
        //删除
        tbGroupActiveMapper.deleteById(activeId);
        return R.OK();
    }
}




